<!--
  - Copyright (c) 2018.
  - 北京九思金信科技有限公司对该文件内容保留所有权利。
  - 未经许可，不得私自拷贝、传播、发布、引用该文件内容，违者将被追究法律责任。
  -->

<template>
    <div v-if="confirmedReportArray.length > 0">
        <el-row style="margin: 1% 0% 1% 0%">
            <el-col :span="4" align="left">
                <span style="font-size:14px; line-height: 26px; color: #747778">财报信息</span>
            </el-col>
        </el-row>
        <ft-tabs v-model="activeName" @tab-click="tabClick" type="border-card">
            <ft-tab-pane v-for="(tableName, index) in tableArray"
                         :label='tableName'
                         :key="index"
                         :name="tableName">
            </ft-tab-pane>
            <!--资产负债表-->
            <el-table v-if="this.activeName === '资产负债表' && handlerAssetDebtArray.length > 0"
                      :data="handlerAssetDebtArray.slice(0, showLines)"
                      class="el-table">
                <el-table-column label="项目名称" prop="reportName" align="left" min-width='200'></el-table-column>
                <el-table-column label="行次" prop="serialNumber" align="left"></el-table-column>
                <el-table-column v-for="(item, index) in assetDebtTerms"
                                 :label="item"
                                 :key="index"
                                 :prop="item"
                                 :formatter="moneyFormatter"
                                 align="right">
                </el-table-column>
                <p v-if="showLines !== maxLines" slot="append" style="text-align:center; line-height:15px;">
                    <a href="javascript:" style="color: rgb(0, 98, 222);" @click="showMoreMData()">点击加载更多</a>
                </p>
            </el-table>
            <!--收入支出表-->
            <el-table v-if="this.activeName === '收入支出表' && handlerInOutArray.length > 0"
                      :data="handlerInOutArray.slice(0, showLines)"
                      class="el-table">
                <el-table-column label="项目名称" prop="reportName" align="left" min-width='200'></el-table-column>
                <el-table-column label="行次" prop="serialNumber" align="left"></el-table-column>
                <el-table-column v-for="(item, index) in inoutTerms"
                                 :label="item"
                                 :key="index"
                                 :prop="item"
                                 :formatter="moneyFormatter"
                                 align="right">
                </el-table-column>
                <p v-if="showLines !== maxLines" slot="append" style="text-align:center; line-height:15px;">
                    <a href="javascript:" style="color: rgb(0, 98, 222);" @click="showMoreMData()">点击加载更多</a>
                </p>

            </el-table>
            <!--利润表-->
            <el-table v-if="this.activeName === '利润表' && handlerProfitArray.length > 0"
                      :data="handlerProfitArray.slice(0, showLines)"
                      class="el-table">
                <el-table-column label="项目名称" prop="reportName" align="left" min-width='200'></el-table-column>
                <el-table-column label="行次" prop="serialNumber" align="left"></el-table-column>
                <el-table-column v-for="(item, index) in profitTerms"
                                 :label="item"
                                 :key="index"
                                 :prop="item"
                                 :formatter="moneyFormatter"
                                 align="right">
                </el-table-column>
                <p v-if="showLines !== maxLines" slot="append" style="text-align:center; line-height:15px;">
                    <a href="javascript:" style="color: rgb(0, 98, 222);" @click="showMoreMData()">点击加载更多</a>
                </p>
            </el-table>
            <!--现金流量表-->
            <el-table v-if="this.activeName === '现金流量表' && handlerCashFlowArray.length > 0"
                      :data="handlerCashFlowArray.slice(0, showLines)"
                      class="el-table">
                <el-table-column label="项目名称" prop="reportName" align="left" min-width='200'></el-table-column>
                <el-table-column label="行次" prop="serialNumber" align="left"></el-table-column>
                <el-table-column v-for="(item, index) in cashFlowTerms"
                                 :label="item"
                                 :key="index"
                                 :prop="item"
                                 :formatter="moneyFormatter"
                                 align="right">
                </el-table-column>
                <p v-if="showLines !== maxLines" slot="append" style="text-align:center; line-height:15px;">
                    <a href="javascript:" style="color: rgb(0, 98, 222);" @click="showMoreMData()">点击加载更多</a>
                </p>
            </el-table>
        </ft-tabs>
    </div>

</template>

<script>
    import * as math from 'mathjs'
    import {ASSET_DEBT_TABLE, IN_OUT_TABLE,
        PROFIT_TABLE, CASH_FLOW_TABLE} from './FinanceReportConstant';

    export default {
        name: 'FinanceReportConfirmedTab',
        props: {
            customerId: '',
        },
        data() {
            return {
                // 默认展示页签
                activeName: ASSET_DEBT_TABLE,
                // 确认过的财报数据
                confirmedReportArray: [],
                // 展示的财报表名
                tableArray: [],
                // 资产负债表数组
                assetDebtTableArray: [],
                // 资产负债表财报期次数组
                assetDebtTerms: [],
                // 财报展示格式的资产负债表
                handlerAssetDebtArray: [],
                // 收入支出表数组
                inOutTableArray: [],
                // 收入支出表财报期次数组
                inoutTerms: [],
                // 财报展示格式的收入支出表
                handlerInOutArray: [],
                // 利润表数组
                profitTableArray: [],
                // 利润表财报期次数组
                profitTerms: [],
                // 财报展示格式的利润表
                handlerProfitArray: [],
                // 现金流量表数组
                cashFlowTableArray: [],
                // 现金流量表财报期次数组
                cashFlowTerms: [],
                // 财报展示格式的现金流量表
                handlerCashFlowArray: [],
                // 默认只展示8行
                showLines: 8,
                // 最大行数
                maxLines: 999,
            }
        },
        mounted() {
            this.loadConfirmedReports()

        },
        methods: {
            // 展示更多数据
            showMoreMData() {
                // -1 指最后一个元素,但不包含最后一个元素，所以不可使用，暂且使用一个大的整数替代
                this.showLines = this.maxLines
            },
            // 切换展示的财报的页签
            tabClick(val) {
                this.activeName = val.name
            },
            // 加载已确认过的财报
            loadConfirmedReports() {
                const url = '/joys-rest/lss-customer/financeReport/' + this.customerId + '/confirmed/list'
                this.$http.get(url).then(
                    resp => {
                        this.confirmedReportArray = resp.body
                        if (this.confirmedReportArray.length === 0) {
                            // 子组件当中修改父组件的visible数据值
                            this.$emit("update:visible",false);
                        } else {
                            this.$emit("update:visible",true);
                        }
                        this.showConfirmedReport()
                    }, resp => {
                        this.$message.error('加载已确认的财报失败')
                    }
                )

            },
            // 展示以确认过的财报
            showConfirmedReport() {
                // 先清除历史数据
                this.clearHistoryData()
                // 确定要展示的报表的名称
                let tableNameSet = new Set(Array.from(this.confirmedReportArray, (report) => report.reportName))
                // 将set集合转换为数组
                this.tableArray = Array.from(tableNameSet).sort((name1, name2) => {
                    // 按照order的顺序进行排列
                    let order = [ASSET_DEBT_TABLE, PROFIT_TABLE, CASH_FLOW_TABLE, IN_OUT_TABLE]
                    return order.indexOf(name1) - order.indexOf(name2)

                })
                // 解析已确认的财报数据
                this.confirmedReportArray.forEach(
                    (report) => {
                        if (report.reportName === ASSET_DEBT_TABLE) {
                            this.assetDebtTableArray.push(report)
                            this.assetDebtTerms.push(report.reportTerm)
                        } else if (report.reportName === IN_OUT_TABLE) {
                            this.inOutTableArray.push(report)
                            this.inoutTerms.push(report.reportTerm)
                        } else if (report.reportName === PROFIT_TABLE) {
                            this.profitTableArray.push(report)
                            this.profitTerms.push(report.reportTerm)
                        } else if (report.reportName === CASH_FLOW_TABLE) {
                            this.cashFlowTableArray.push(report)
                            this.cashFlowTerms.push(report.reportTerm)
                        }
                    }
                )
                this.sortArrayData()

                // 组装数据成为 [{reportName:"name", serialNumber: "number", 报表期间1:"value1",
                //             报表期间2:"value2",报表期间3:"value3",报表期间4:"value4"},...] 的格式
                // 组装资产负债表
                if (this.assetDebtTableArray.length > 0) {
                    for (let i = 0; i < this.assetDebtTableArray[0].dataList.length; i++) {
                        // 需要拼装成的对象
                        if (this.handlerAssetDebtArray[i] === undefined) {
                            // 在数组中创建一个对象
                            this.handlerAssetDebtArray[i] = {}
                        }
                        // 序号和项目名称都是相同的
                        this.handlerAssetDebtArray[i].serialNumber = this.assetDebtTableArray[0].dataList[i].serialNumber
                        this.handlerAssetDebtArray[i].reportName = this.assetDebtTableArray[0].dataList[i].reportName
                        // 赋值不同报表期次时的项目值
                        for (let j = 0; j < this.assetDebtTerms.length; j++) {
                            let currentReportTime = this.assetDebtTerms[j]
                            for (let k = 0; k < this.assetDebtTableArray.length; k++) {
                                if (this.assetDebtTableArray[k].reportTerm === currentReportTime
                                    && this.assetDebtTableArray[k].dataList[i]) {
                                    this.handlerAssetDebtArray[i][currentReportTime] =
                                        this.assetDebtTableArray[k].dataList[i].reportValue
                                    break;
                                }
                            }
                        }
                    }
                }

                // 组装收入支出表
                if (this.inOutTableArray.length > 0) {
                    for (let i = 0; i < this.inOutTableArray[0].dataList.length; i++) {
                        // 需要拼装成的对象
                        if (this.handlerInOutArray[i] === undefined) {
                            // 在数组中创建一个对象
                            this.handlerInOutArray[i] = {}
                        }
                        // 序号和项目名称都是相同的
                        this.handlerInOutArray[i].serialNumber = this.inOutTableArray[0].dataList[i].serialNumber
                        this.handlerInOutArray[i].reportName = this.inOutTableArray[0].dataList[i].reportName
                        // 赋值不同报表期次时的项目值
                        for (let j = 0; j < this.inoutTerms.length; j++) {
                            let currentReportTime = this.inoutTerms[j]
                            for (let k = 0; k < this.inOutTableArray.length; k++) {
                                if (this.inOutTableArray[k].reportTerm === currentReportTime
                                    && this.inOutTableArray[k].dataList[i]) {
                                    this.handlerInOutArray[i][currentReportTime] =
                                        this.inOutTableArray[k].dataList[i].reportValue
                                    break;
                                }
                            }
                        }
                    }
                }

                // 组装利润表
                if (this.profitTableArray.length > 0) {
                    for (let i = 0; i < this.profitTableArray[0].dataList.length; i++) {
                        // 需要拼装成的对象
                        if (this.handlerProfitArray[i] === undefined) {
                            // 在数组中创建一个对象
                            this.handlerProfitArray[i] = {}
                        }
                        // 序号和项目名称都是相同的
                        this.handlerProfitArray[i].serialNumber = this.profitTableArray[0].dataList[i].serialNumber
                        this.handlerProfitArray[i].reportName = this.profitTableArray[0].dataList[i].reportName
                        // 赋值不同报表期次时的项目值
                        for (let j = 0; j < this.profitTerms.length; j++) {
                            let currentReportTime = this.profitTerms[j]
                            for (let k = 0; k < this.profitTableArray.length; k++) {
                                if (this.profitTableArray[k].reportTerm === currentReportTime
                                    && this.profitTableArray[k].dataList[i]) {
                                    this.handlerProfitArray[i][currentReportTime] =
                                        this.profitTableArray[k].dataList[i].reportValue
                                    break;
                                }
                            }
                        }
                    }
                }

                // 组装现金流量表
                if (this.cashFlowTableArray.length > 0) {
                    for (let i = 0; i < this.cashFlowTableArray[0].dataList.length; i++) {
                        // 需要拼装成的对象
                        if (this.handlerCashFlowArray[i] === undefined) {
                            // 在数组中创建一个对象
                            this.handlerCashFlowArray[i] = {}
                        }
                        // 序号和项目名称都是相同的
                        this.handlerCashFlowArray[i].serialNumber = this.cashFlowTableArray[0].dataList[i].serialNumber
                        this.handlerCashFlowArray[i].reportName = this.cashFlowTableArray[0].dataList[i].reportName
                        // 赋值不同报表期次时的项目值
                        for (let j = 0; j < this.cashFlowTerms.length; j++) {
                            let currentReportTime = this.cashFlowTerms[j]

                            for (let k = 0; k < this.cashFlowTableArray.length; k++) {
                                if (this.cashFlowTableArray[k].reportTerm === currentReportTime
                                    && this.cashFlowTableArray[k].dataList[i]) {
                                    this.handlerCashFlowArray[i][currentReportTime] =
                                        this.cashFlowTableArray[k].dataList[i].reportValue
                                    break;
                                }
                            }
                        }
                    }
                }

            },
            // 排序
            sortArrayData() {
                // 报表期次排序 三年一期， 三年年报排在前面，最后一期排在最后
                let compareTerm = function (reportTerm1, reportTerm2) {
                    if (reportTerm1.trim().length < reportTerm2.trim().length) {
                        return -1
                    } else if (reportTerm1.trim().length === reportTerm2.trim().length) {
                        if (reportTerm1 <= reportTerm2) {
                            return -1
                        } else {
                            return 1
                        }
                    } else {
                        return 1
                    }
                }
                let compareObj = function (obj1, obj2) {
                    if (obj1.reportTerm.trim().length < obj2.reportTerm.trim().length) {
                        return -1
                    } else if (obj1.reportTerm.trim().length === obj2.reportTerm.trim().length) {
                        if (obj1.reportTerm <= obj2.reportTerm) {
                            return -1
                        } else {
                            return 1
                        }
                    } else {
                        return 1
                    }
                }
                this.assetDebtTerms.sort(compareTerm)
                this.assetDebtTableArray.sort(compareObj)
                this.inoutTerms.sort(compareTerm)
                this.inOutTableArray.sort(compareObj)
                this.profitTerms.sort(compareTerm)
                this.profitTableArray.sort(compareObj)
                this.cashFlowTerms.sort(compareTerm)
                this.cashFlowTableArray.sort(compareObj)
            },
            clearHistoryData() {
                this.assetDebtTableArray = []
                this.inOutTableArray = []
                this.profitTableArray = []
                this.cashFlowTableArray = []
                this.assetDebtTerms = []
                this.inoutTerms = []
                this.profitTerms = []
                this.cashFlowTerms = []
                this.handlerAssetDebtArray = []
                this.handlerInOutArray = []
                this.handlerProfitArray = []
                this.handlerCashFlowArray = []
            },
            // 去除字符串两端的空格
            trim() {
                return this.replace(/(^\s*)|(\s*$)/g, '')
            },

            //金额类型转换
            moneyFormatter: function (row, column) {
                var val = row[column.property]
                if (this.isRealNum(val)) {
                    const valMultiple = math.multiply(val, 100)
                    const roundVal = math.round(valMultiple)
                    val = math.divide(roundVal, 100)
                    val = this.formatNum(val)
                    val = val.toString()
                    //补位保留两位小数
                    if(val.indexOf('.') === -1){
                        val = val + '.00'
                    }
                    if(val.length - val.indexOf('.') === 2){
                        val = val + '0'
                    }
                    return val
                }
                return val
            },
            //数字判断
            isRealNum(val) {
                // isNaN()函数 把空串 空格 以及NUll 按照0来处理 所以先去除
                if (val === "" || val == null) {
                    return false
                }
                if (!isNaN(val)) {
                    return true
                } else {
                    return false
                }
            },
            //千分符
            formatNum(strNum) {
                if (strNum.length <= 3) {
                    return strNum
                }
                if (!/^(\+-)?(\d+)(\.\d+)?$/.test(strNum)) {
                    return strNum
                }
                // array需要先定义，再使用，不然报ReferenceError，因为let不存在变量提升
                let array
                array = strNum.toString().split('.')
                let reg =/\d{1,3}(?=(\d{3})+$)/g;
                array[0] = array[0].toString().replace(reg, '$&,');
                return array.join('.')
            },
        }

    }

</script>

<style>
    .el-table .cell {
        white-space: pre-wrap;
    }
</style>
